package com.scalar.chiptrack.sales.actions;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.db.DBXException;
import com.scalar.chiptrack.operations.process.dao.NewProductDAO;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.sales.SOShippingLocation;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.NewSalesOrderDAO;
import com.scalar.chiptrack.sales.forms.ShippingLocationforSOForm;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.utils.AutoGrowingArrayList;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * User: Sujan
 * Date: Nov 16, 2007
 * Time: 3:42:13 PM
 */
public class ShippingLocationforSOAction extends ChipTrackAction
{
    private final String ACTION_NAME = "/shippingLocationforSOAction.do";

    public ActionForward execute (ActionMapping mapping,
                                          ActionForm form,
                                          HttpServletRequest request,
                                          HttpServletResponse response)
                                         throws Exception
    {
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute (SessionKeys.USER_KEY);
        if (user == null)
        {
            session.setAttribute (SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString());
            return (mapping.findForward ("login"));
        }
        HashMap errors = new HashMap();
        request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
        HashMap info = new HashMap();
        request.setAttribute (SessionKeys.INFO_MESSAGES, info);
        ShippingLocationforSOForm shippingLocationforSOForm = (ShippingLocationforSOForm) form;
		String action = request.getParameter("action");
        if ( action == null || action.trim().length() == 0 )
        {
            action = "search";
        }

        if ( "search".equalsIgnoreCase( action ) )
        {
            request.setAttribute ( "customerList", CustomerDAO.getAllCustomerNames () );
            request.setAttribute ( "productList", NewProductDAO.loadPartNumbers( null, 0, Constants.LOCATION_TYPE_FG, true, true, false, 0 ) );
            return ( mapping.findForward ("search") );
        }
        else if ( "submitSearch".equalsIgnoreCase( action ) )
        {

            AutoGrowingArrayList salesOrderList = new AutoGrowingArrayList( SOShippingLocation.class );
            salesOrderList.addAll( NewSalesOrderDAO.loadSalesOrdersForShipLocatoins ( null, shippingLocationforSOForm.getProductId(), shippingLocationforSOForm.getCustomerId(), shippingLocationforSOForm.getSalesOrderNo(), shippingLocationforSOForm.getScheduledInDays(), shippingLocationforSOForm.isShowOnlyNoShipLocationSOs(), shippingLocationforSOForm.getIsSample()  ) );

            shippingLocationforSOForm.setSalesOrderList( salesOrderList );
            request.setAttribute( "locationList", VendorDAO.getFinishedGoodsLocations() );
            saveToken(request);
            return ( mapping.findForward ("selectShippingLocation") );
        }
        else if ( "save".equalsIgnoreCase( action ) )
        {
            if ( isTokenValid(request) )
            {
                DBTransaction dbTransaction = null;
                boolean success = false;
                try
                {
                    dbTransaction = DBTransaction.getInstance();
                    dbTransaction.begin();
                    NewSalesOrderDAO.saveSalesOrderShipLocatoins( dbTransaction, shippingLocationforSOForm.getSalesOrderList() );
                    if ( dbTransaction != null )
                    {
                        dbTransaction.commit();
                    }
                    success = true;
                    info.put( "Sales Order Shipping Locations saved successfully", null );
                }
                catch ( Exception e )
                {
                    e.printStackTrace();
                    errors.put ( "Could not save Sales Order Shipping Locations", null );
                }
                finally
                {
                    if ( dbTransaction != null && !success )
                    {
                        try
                        {
                            dbTransaction.rollback();
                        } catch ( DBXException ignore ) {}
                    }
                }
            }
            else
            {
                errors.put ( "Invalid request, Please try again.", null );
            }
            request.setAttribute ( "customerList", CustomerDAO.getAllCustomerNames () );
            request.setAttribute ( "productList", NewProductDAO.loadPartNumbers( null, 0, Constants.LOCATION_TYPE_FG, true, true, false, 0 ) );
            return ( mapping.findForward ("search") );
        }

        return null;        
    }
}
